﻿using MES.Desktop.Common;
using MES.Desktop.Entities;
using MES.Desktop.IService;
using MES.Desktop.Models;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace MES.Desktop.ViewModels
{
    public class MainViewModel : BindableBase
    {
        Entities.UserEntity _currentUser;

        public UserModel UserInfo { get; set; } = new UserModel();


        private Entities.MenuEntity[] menus;

        public ObservableCollection<MenuModel> Menus { get; set; } =
            new ObservableCollection<MenuModel>();
        public ObservableCollection<MenuModel> SubMenus { get; set; } =
            new ObservableCollection<MenuModel>();
        public DelegateCommand<MenuModel> MainMenuButtonCommand { get; set; }

        public DelegateCommand<MenuModel> NavigationCommand { get; set; }
        private bool _isShowLoading;

        public bool IsShowLoading
        {
            get { return _isShowLoading; }
            set
            {
                SetProperty<bool>(ref _isShowLoading, value);
                if (value) Blur = 12;
                else Blur = 0;
            }
        }
        private int _blur = 0;

        public int Blur
        {
            get { return _blur; }
            set { SetProperty<int>(ref _blur, value); }
        }
        private string _loadingTip = "正在加载...";

        public string LoadingTip
        {
            get { return _loadingTip; }
            set { SetProperty<string>(ref _loadingTip, value); }
        }
        GlobalValues _globalValues;
        IMenuService _menuService;
        public MainViewModel(
            IDialogService dialogService,
            GlobalValues globalValues,
            IRegionManager regionManager,
            IEventAggregator eventAggregator,
            IMenuService menuService)
        {
            _menuService = menuService;
            _globalValues = globalValues;

            dialogService.ShowDialog("LoginView", result =>
            {
                if (result.Result != ButtonResult.OK)
                {
                    System.Environment.Exit(0);
                }
                _currentUser = result.Parameters.GetValue<Entities.UserEntity>("user");
            });
            //http://localhost:5185/api/file/img/a01.jpg
            UserInfo.RealName = _currentUser.realName;
            UserInfo.Icon = $"{_globalValues.ServerHost}/api/file/img/{_currentUser.eIcon}";


            this.LoadMenu();
            MainMenuButtonCommand = new DelegateCommand<MenuModel>(model =>
            {
                SubMenus.Clear();
                foreach (var item in model.Children)
                    SubMenus.Add(item);
            });

            NavigationCommand = new DelegateCommand<MenuModel>(model =>
            {
                //model.MenuRoute
                NavigationParameters nps = new NavigationParameters();
                nps.Add("route", model.MenuRoute);
                nps.Add("funcs", model.Funcs);
                regionManager.RequestNavigate(
                    "MainRegion",
                    model.TargetView,
                    nps);
            });

            eventAggregator.GetEvent<LoadingEvent>()
               .Subscribe(tip =>
               {
                   // 显示或隐藏Loading动画
                   IsShowLoading = !IsShowLoading;
                   this.LoadingTip = tip;
               });
        }

        private void LoadMenu()
        {
            Task.Run(() =>
            {
                var rids = _currentUser.roles
                           .Select(r => r.roleId).ToArray();
                menus = _menuService.GetMenuByRoles(rids).ToArray();

                var l1 = menus.Where(m => m.ParentId == "-1").ToList();
                foreach (var item in l1)
                {
                    var l2 = menus.Where(m => m.ParentId == item.MenuId).ToList()
                        .Select(m => new MenuModel
                        {
                            MenuHeader = m.MenuHeader,
                            MenuIcon = ((char)int.Parse(item.MenuIcon, NumberStyles.HexNumber)).ToString(),
                            TargetView = m.TargetView,
                            MenuRoute = $"MES系统/{item.MenuHeader}/{m.MenuHeader}",
                            Funcs = m.Funcs
                        }).ToList();

                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        Menus.Add(new MenuModel
                        {
                            MenuHeader = item.MenuHeader,
                            MenuIcon = ((char)int.Parse(item.MenuIcon, NumberStyles.HexNumber)).ToString(),
                            Children = l2
                        });
                    });
                }

                Menus[0].IsSelected = true;
                Application.Current.Dispatcher.Invoke(() =>
                {
                    foreach (var item in Menus[0].Children)
                        SubMenus.Add(item);
                });
            });
        }
    }
}
